<?php

namespace App\Console\Commands;

use App\Enum\MonitorEnum;
use App\Enum\OrderEnum;
use App\Enum\ThirdImportEnum;
use App\Enum\ThirdOrderEnum;
use App\Models\ThirdImportBatchModel;
use App\Models\ThirdImportDetailModel;
use App\Models\ThirdOrderAllModel;
use App\Services\MapService;
use App\Services\MonitorService;
use App\Services\Tools\HelpService;
use App\Services\VehicleConfigService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ImmigrateImportOrdersCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:immigrate-import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '将Excel订单同步到三方订单总表。';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $batch = ThirdImportBatchModel::query()->where(['status' => ThirdImportEnum::BATCH_STATUS_IMPORT])
            ->select(['id','batch_no'])
            ->orderBy('updated_at')->first();

        if( empty($batch) ) return 0;

        try {
            // 将批次改为导入进行中
            $batch->update(['status' => ThirdImportEnum::BATCH_STATUS_IMPORTING]);

            $fields = ['city_code', 'user_phone'
                , 'start_address', 'start_adcode',  'start_address_detail', 'start_location'
                , 'end_address', 'end_adcode','end_address_detail', 'end_location'
                ,'vehicle_type', 'vehicle_use_type', 'start_time', 'distance', 'duration'
                ,'platform_id', 'third_order_no', 'flight_no','id'
            ];
            // 取得明细
            $rows = ThirdImportDetailModel::query()->where(['batch_no' => $batch['batch_no']
                ,'valid_status'=>ThirdImportEnum::DETAIL_VALID_STATUS_OK
                ,'transfer_status'=>ThirdImportEnum::DETAIL_TRANSFER_STATUS_NO
            ])->select($fields)->get();

            foreach ($rows as $row) {
                // 导入订单
                $this->_importOrder($row->toArray());
                // 更新明细为已经传递
                $row->update(['transfer_status'=>ThirdImportEnum::DETAIL_TRANSFER_STATUS_YES]);
                usleep(500000);
            }

            // 标记批次已经完结
            $batch->update(['status'=>ThirdImportEnum::BATCH_STATUS_IMPORT_YES,'done_time'=>time()]);

            return 0;
        }catch (Exception $e){
            $this->_exceptionMonitor(sprintf('批次号(%s)，E=%s.',$batch['batch_no'], $e->getMessage()));
            // 标记批次 要再次导入
            $batch->update(['status'=>ThirdImportEnum::BATCH_STATUS_IMPORT_ERROR,'memo'=>$e->getMessage()]);
            Log::error( $e->getMessage());
            return 1;
        }
    }
    private function _exceptionMonitor( string $memo )
    {
        MonitorService::addException(MonitorEnum::MONITOR_TYPE_IMPORT_TO_THIRD, $memo);
    }

    /**
     * 导入单条数据
     *
     * @param array $data
     * @return void
     * @throws Exception
     */
    private function _importOrder( array $data ): void
    {
        try {
            $unsetFields = ['id'];
            foreach( $unsetFields as $field) unset($data[$field]);
            // 增加订单时长的距离计算
            $data = $this->_locationsDistance($data);

            $data['order_no'] = HelpService::createOrderNum();
            $data['amount'] = VehicleConfigService::platformAmount($data['platform_id'],$data['city_code'], $data['distance'], $data['vehicle_use_type'], $data['vehicle_type'], OrderEnum::ORDER_PAY_OFFLINE_PAYMENT);
            $data['amount_type'] = $data['payment_method'] = OrderEnum::ORDER_PAY_OFFLINE_PAYMENT;
            $data['user_id'] = $data['user_id'] ?? env('BUSINESS_ORDER_USER_ID');
            $data['order_source'] = ThirdOrderEnum::THIRD_ORDER_SOURCE_IMPORT;

            ThirdOrderAllModel::create($data);

        }catch (Exception $e){
            throw new Exception(sprintf("生成三方订单(%s)异常：%s", $data['third_order_no'], $e->getMessage()));
        }
    }

    /**
     * 获取两点的距离
     *
     * @param $updateData
     * @return mixed
     * @throws Exception
     */
    private function _locationsDistance($updateData)
    {
        $result = MapService::distanceBetweenLocations($updateData['start_location'], $updateData['end_location']);
        $result = $result['rows'][0]['elements'][0];
        $updateData['duration'] = $result['duration'];
        $updateData['distance'] = $result['distance'];
        return $updateData;
    }
}
